﻿using CoreSolution.Tools.WebResult;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace CoreSolution.Vip.Interceptor
{
    /// <summary>
    /// 数据模型验证过滤器
    /// </summary>
    public class ModelFilter : ActionFilterAttribute
    {
        public ModelFilter()
        {

        }
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            StringBuilder err = new StringBuilder();
            if (context.ModelState.IsValid)
            {
                await base.OnActionExecutionAsync(context, next);
            }
            else
            {
                foreach (var s in context.ModelState.Values)
                {
                    foreach (var p in s.Errors)
                    {
                        err.AppendFormat("{0}\\n", p.ErrorMessage);
                    }
                }

                context.Result = AjaxHelper.JsonResult(HttpStatusCode.Forbidden, "请求被阻止，缺少必须规则", err);
                return;
            }
        }
    }
}
